#include <string>
#include <windows.h>  // 用于 GetTickCount 函数
#include <graphics.h> // 若使用 EasyX 图形库
#include "TextBox.h"  // 自定义的 TextBox 类头文件


// 构造函数，初始化成员变量
TextBox::TextBox(int x, int y, int width, int height, int maxWord,int style)
    : x(x), y(y), width(width), height(height), maxWord(maxWord), style(style),
    text(L""), isSelected(false), showCursor(false),
    //,text_len(0), Outtextxy()
    cursorPos(0), backspace(false),
    firstX(x), firstY(y), firstWidth(width), firstHeight(height), placeholderTextBig(0),
    secondX(x/2), secondY(y/2), secondWidth(width/2), secondHeight(height/2),
    placeholderText(L""), borderRadius(5), buttonWidth(40), firstplaceholderTextBig(0),secondplaceholderTextBig(0),
    ellipseWidth(20),ellipseHeight(height)
{}

// 获取文本内容（添加 const）
wstring TextBox::getText() const {
    return text;
}

// 获取是否被选中的状态（添加 const）
bool TextBox::getSelect() {
    return isSelected;
}

// 判断文本框是否为空（添加 const）
bool TextBox::isEmpty() const {
    return text.empty();
}

// 清空文本框内容
void TextBox::clear() {
    text = L"";
    cursorPos = 0;
}

// 设置文本框内容（优化为 const 引用）
void TextBox::setText(const wstring& newText) {
    text = newText;
    cursorPos = text.length();
}

// 设置下一个输入框
void TextBox::setNextField(TextBox* next) {
    nextField = next;
}

//  设置第一默认文本
void TextBox::setDefaultText(const wstring& newText,int TextBig) {
    placeholderText = newText;
    placeholderTextBig = TextBig;
}
//  设置第二默认文本大小
void TextBox::setSecondDefaultText(int _placeholderTextBig) {
    secondplaceholderTextBig = _placeholderTextBig;
}
//  设置组件小窗口的位置
void TextBox::setSecondPosition(int x, int y, int width, int height) {
    secondX = x;
    secondY = y;
    secondWidth = width;
    secondHeight = height;
}

void TextBox::updateSecond() {
    x ^= firstX ^ secondX;
    y ^= firstY ^ secondY;
    width ^= firstWidth ^ secondWidth;
    height ^= firstHeight ^ secondHeight;
    placeholderTextBig ^= secondplaceholderTextBig ^ firstplaceholderTextBig;
}

void TextBox::drawBorderedRoundRect(
    int left,int top,int right,int bottom,
    COLORREF fillColor,COLORREF borderColor,
    //int ellipseWidth ,int ellipseHeight,
    int borderWidth )
{
    // 保存原始绘图设置
    LINESTYLE oldLineStyle;
    getlinestyle(&oldLineStyle);  // 正确获取当前线型设置
    COLORREF oldFillColor = getfillcolor();
    COLORREF oldLineColor = getlinecolor();

    // 绘制填充部分
    setfillcolor(fillColor);
    solidroundrect(left, top, right, bottom, ellipseWidth, ellipseHeight);

    // 绘制边框
    setlinestyle(PS_SOLID, borderWidth);  // 设置边框粗细
    setlinecolor(borderColor);
    roundrect(left, top, right, bottom, ellipseWidth, ellipseHeight);

    // 恢复原始设置
    setlinestyle(&oldLineStyle);  // 恢复原始线型
    setfillcolor(oldFillColor);
    setlinecolor(oldLineColor);
}




// 绘制文本框
void TextBox::draw() {
    setfillcolor(WHITE);
    if (isSelected) {
        setlinecolor(RGB(0, 120, 215));
    }
    else {
        setlinecolor(RGB(122, 122, 122));
    }
    if (style == 1) {
        fillrectangle(x, y, x + width, y + height);
    }
    else {
        drawBorderedRoundRect(x, y, x + width, y + height);
    }
    //solidroundrect(x, y, x + width, y + height);
    //text_len = autoAdjustText(x+8,y + (height - textheight(_T("微软雅黑") ) ) / 2, width - 5, textheight(_T("微软雅黑")), text);

    // 绘制提示文字
    if (text.empty() && !isSelected) {
        settextcolor(RGB(180, 180, 180));
        settextstyle(placeholderTextBig, 0, _T("宋体"));
        outtextxy(x + 5, y + (height - textheight(_T("宋体"))) / 2, placeholderText.c_str());
        return ;
    }

    settextcolor(BLACK);
    setbkmode(TRANSPARENT);
    settextstyle(height * 4 / 5, 0, _T("微软雅黑"));

    outtextxy(x + 5, y + (height - textheight(_T("微软雅黑"))) / 2, text.c_str());

    if (isSelected && showCursor) {
        int cursorX = x + 5 + textwidth(text.substr(0, cursorPos).c_str());
        line(cursorX, y + 2 + height / 8, cursorX, y + height * 7 / 8 - 2);
    }
}

// 检查鼠标点击事件
bool TextBox::checkClick(int mouseX, int mouseY) {
    if (mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height) {
        isSelected = true;
        return true;
    }
    isSelected = false;
    cursorPos = text.length();
    return false;
}

// 处理键盘输入事件
bool TextBox::keyInput(wchar_t ch) {
    if (isSelected) {
        switch (ch) {
        case '\b':  // 退格键
            if (!text.empty() && cursorPos > 0) {
                text.erase(cursorPos - 1, 1);
                cursorPos--;
            }
            break;
        case '\r':  // 回车键
        case '\n':
            cursorPos = text.length();
            isSelected = false;      // 取消当前焦点
            if (onFinalEnter) {
                onFinalEnter(); // 执行最终确认操作
            }
            if (nextField) {
                nextField->isSelected = true; // 激活下一个输入框
            }
            break;
        default:    // 其他输入
            if (backspace) {
                backspace = false;
            }
            else {
                if (text.length() < maxWord) {
                    text.insert(cursorPos, 1, ch);
                    cursorPos++;
                }
            }
            break;
        }
        return true;
    }
    return false;
}

// 在 TextBox 类中添加处理函数
bool TextBox::handleKeyEvent(int vkCode) {
    if (!isSelected) return false;

    switch (vkCode) {
    case VK_LEFT:
        if (cursorPos > 0) cursorPos--;
        return true;
    case VK_RIGHT:
        if (cursorPos < text.length()) cursorPos++;
        return true;
    case VK_HOME:
        cursorPos = 0;
        return true;
    case VK_END:
        cursorPos = text.length();
        return true;
    default:
        return false;
    }
}

// 更新光标状态
void TextBox::updateCursor() {
    static DWORD lastTick = GetTickCount();
    DWORD currentTick = GetTickCount();
    if (currentTick - lastTick >= 500) { // 每500ms切换一次
        showCursor = !showCursor;
        lastTick = currentTick;
    }
}

// 设置最终确认回调
void TextBox::setFinalCallback(const function<void()>& callback) {
    onFinalEnter = callback;
}